跳到主要内容

200 岛屿数量

https://leetcode.cn/leetbook/read/top-interview-questions-medium/xvtsnm/

cost: 17m19s

class Solution {
public:
int numIslands(vector<vector<char>>& grid) {
int res = 0;
vector<vector<int>> memo(grid.size(), vector<int>(grid[0].size()));
for (int i = 0; i < grid.size(); i++) {
for (int j = 0; j < grid[0].size(); j++) {
if (memo[i][j]) {
continue;
}
if (grid[i][j] == '0') {
continue;
}
memo[i][j] = 1;
this->walk(grid, memo, i, j);
res++;
}
}
return res;
}

private:
void walk(vector<vector<char>>& grid, vector<vector<int>>& memo, int i,
int j) {
if (i >= 1) {
if (grid[i - 1][j] == '1' && memo[i - 1][j] == 0) {
memo[i - 1][j] = 1;
this->walk(grid, memo, i - 1, j);
}
}
if (j >= 1) {
if (grid[i][j - 1] == '1' && memo[i][j - 1] == 0) {
memo[i][j - 1] = 1;
this->walk(grid, memo, i, j - 1);
}
}
if (i < grid.size() - 1) {
if (grid[i + 1][j] == '1' && memo[i + 1][j] == 0) {
memo[i + 1][j] = 1;
this->walk(grid, memo, i + 1, j);
}
}
if (j < grid[0].size() - 1) {
if (grid[i][j + 1] == '1' && memo[i][j + 1] == 0) {
memo[i][j + 1] = 1;
this->walk(grid, memo, i, j + 1);
}
}
}
};